package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/httpmvc/service"
	"gitee.com/sansaniot/ssiot-core/msg/sms"
	"ssadmin/common/constant"
	"ssadmin/internal/admin/models/command"
)

type VerifyCode struct {
	service.Service
}

func (e *VerifyCode) ValidCode(req *command.PasswordForgetResetReq) (err error) {
	//缓存验证码
	cacheKey := fmt.Sprintf("%s%s", constant.PrefixAuthCode, req.Mobile)
	data, _ := env.Cache.Get(cacheKey)
	if len(data) == 0 {
		return errors.New("验证码过期或者无效")
	}
	m := make(map[string]string)
	_ = json.Unmarshal([]byte(data), &m)
	if m["code"] != req.Code {
		return errors.New("验证码过期或者无效")
	}
	return nil
}

func (e *VerifyCode) CacheCode(req *command.VerifyCodeReq, verifyCode string) (err error) {
	//缓存验证码
	cacheKey := fmt.Sprintf("%s%s", constant.PrefixAuthCode, req.Identifier)
	cacheVal := make(map[string]interface{})
	cacheVal["identifier"] = req.Identifier
	cacheVal["code"] = verifyCode
	bytes, _ := json.Marshal(cacheVal)
	return env.Cache.Set(cacheKey, string(bytes), 300)
}

// SendCode 发送验证码
//@msgCode 消息类型code see msgtype.MsgType
func (e *VerifyCode) SendCode(req *command.VerifyCodeReq) (err error) {
	_ = sms.InitSMSConfig(&sms.SMSConfig{
		AccessKeyId:     env.ConfigOperator.GetString("ssiot.sms.accessKeyId"),
		AccessKeySecret: env.ConfigOperator.GetString("ssiot.sms.accessSecret"),
		SignName:        env.ConfigOperator.GetString("ssiot.sms.signName"),
	})

	err = sms.SendSMS(sms.SMSParam{
		Phone: req.Identifier,
		Data:  req.Data,
	}, req.MsgCode)

	if err != nil {
		return
	}
	return
}
